package com.example.cloudmusic.home.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.cloudmusic.databinding.ItemPersonalPlaylistBinding
import com.example.cloudmusic.home.model.Playlist
import com.example.cm_utils.FormatUtils

/**
 * 歌单、专辑卡片适配器
 */
class PersonalPlaylistAdapter : BaseListAdapter<Playlist, PersonalPlaylistAdapter.ViewHolder>(PlaylistDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemPersonalPlaylistBinding.inflate(
                LayoutInflater.from(parent.context), parent, false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class ViewHolder(private val binding: ItemPersonalPlaylistBinding) :
        RecyclerView.ViewHolder(binding.root) {

        init {
            binding.root.setOnClickListener { onItemClick(adapterPosition) }
        }

        fun bind(item: Playlist) {
            binding.apply {
                cmPlaylistTitle.text = item.title
                cmPlaylistDescription.text = item.description
                cmPlayCountText.text = FormatUtils.formatPlayCount(item.playCount)

                Glide.with(root)
                    .load(item.imageUrl)
                    .into(cmCoverImage)
            }
        }
    }

    private class PlaylistDiffCallback : DiffUtil.ItemCallback<Playlist>() {
        override fun areItemsTheSame(oldItem: Playlist, newItem: Playlist): Boolean =
            oldItem.id == newItem.id

        override fun areContentsTheSame(oldItem: Playlist, newItem: Playlist): Boolean =
            oldItem.title == newItem.title &&
                    oldItem.description == newItem.description &&
                    oldItem.playCount == newItem.playCount &&
                    oldItem.imageUrl == newItem.imageUrl
    }
}